<template>
  <div v-loading="loading" class="readOver">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="isDeal" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              parameters="deal"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('创建人')" prop="user.userId">
            <UserSelect
              v-model="form.user.userId"
              :placeholder="$t('创建人')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发生时间')" prop="happenTime">
            <DatePicker v-model="form.happenTime" :placeholder="$t('发生时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('评价类型')" prop="itemType">
            <dictSelect
              ref="dict"
              v-model="form.itemType"
              :clearable="true"
              dictionary="evaluation_type"
              :is-check="false"
              @change="onchange"
            />
          </el-form-item>
        </el-col>
        <el-col v-for="(item,index) in form.fields" :key="index" :span="24">
          <el-form-item :label="$t(item.fieldLabel)" :prop="'fields.'+index+'.content'" :rules="{required: true, message:$t('必填信息'), trigger:['blur','change']}">
            <EditorTxt v-if="!loading" v-model="(form.fields)[index].content" :height="300" />
            <!--            <el-input v-model="form.details" type="textarea" :autosize="{ minRows: 6 }" maxlength="2000" show-word-limit :placeholder="$t('详细情况')" />-->
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" has-permi="afterInvest:evaluation" data-type="deal_after_invest_evaluation" :business-id="form.dealId" :btn-show="!btnHide" />
    </el-form>
    <div v-if="!btnHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <FormBtn v-if="useProcess" ref="formBtn" :bus-data="form" has-permi="afterInvest:evaluation" :menu-key="menuKey" />
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn v-if="!useProcess" has-permi="afterInvest:evaluation" />
    </div>
  </div>
</template>

<script>
    import MainBodySelect from '@/components/MainBodySelect'
    import EditorTxt from '@/components/Tinymce'
    import {
      getDealAfterInvestEvaluation,
      saveDealAfterInvestEvaluation
    } from '@/api/afterInvest/evaluation/dealAfterInvestEvaluation'
    import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
    import { getDealName } from '@/api/base/deal/dealBase'
    export default {
      components: {
        MainBodySelect,
        EditorTxt
      },
      props: {
        dealId: {
          type: String,
          default: undefined
        },
        isDeal: {
          type: Boolean,
          default: true
        }
      },
        data() {
            return {
                // 菜单标识
                menuKey: 'after_evaluation',
                // 是否配置了流程
                useProcess: false,
                otherBtnHide: false,
                // 评价类型 字典item_type字典
                itemTypeOptions: [], // 跟踪方式 字典evaluation_type
                trackModeOptions: [], // 表单参数
                // 是否显示MainBodySelect组件
                form: {
                  fileList: [],
                  user: {
                    userId: undefined
                  }
                },
                // 是否隐藏保存等按钮
                btnHide: false,
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                  dealId: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  'user.userId': [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  happenTime: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ],
                  itemType: [
                    { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
                  ]
                },
                dealSuperviseOptions: [],
                saveField: undefined,
                saveFieldData: []
            }
        },
        created() {
          this.$bus.$emit('async_done')
          // 查询是否配置了流程
          this.getUseProcess()
          this.getDicts('evaluation_type').then(response => {
            this.itemTypeOptions = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
              console.log(data)
                if (data != null && data.id !== undefined) {
                    getDealAfterInvestEvaluation(data.id).then(response => {
                      console.log(response.data.itemType, response.data.fields)
                        this.form.itemType = undefined
                        this.saveField = response.data.itemType
                        this.saveFieldData = response.data.fields
                        this.form = response.data
                        this.loading = false
                    })
                } else {
                  this.reset()
                  if (this.dealId) {
                    this.form.dealId = this.dealId
                  } else if (this.$route.query.id) {
                    this.form.dealId = this.$route.query.id
                  }
                  this.loading = false
                }
            },
          // 初始化数据
          remindersInit(data) {
            this.loading = true
            this.reset()
            if (data != null) {
              this.form.dealId = data.dealId
              this.loading = false
            }
          },
          // 获取字典
          onchange(e) {
              console.log(e, this.saveField, this.saveFieldData)
            if (e === this.saveField && this.saveFieldData && this.saveFieldData.length > 0) {
              this.form.fields = this.saveFieldData
              return
            }
            this.form.fields = []
            var dict = this.$refs.dict.currentDict
            if (dict && dict.childDict) {
              console.log(dict)
              // 获取字段展示
              this.getDicts(dict.childDict).then(res => {
                res.data.content = undefined
                res.data.fieldName = undefined
                res.data.forEach(item => {
                  item.content = item.remark
                  item.fieldName = item.dictValue
                  item.fieldLabel = item.dictLabel
                  item.id = undefined
                })
                this.form.fields = res.data
              })
            }
          },

          // 表单重置
            reset() {
              this.form = {
                id: undefined,
                user: {
                  userId: this.$store.state.user.userId
                },
                dealId: undefined,
                happenTime: new Date(),
                itemType: undefined,
                fileList: [],
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                fields: [],
                actId: undefined,
                actStatus: undefined
              }
              this.resetForm('form')
            },
            // 取消按钮
            cancel() {
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              if (this.$parent.$parent.reset !== undefined) {
                this.$parent.$parent.reset()
              }
            },
            // 关闭form页面
            closeForm() {
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              // 刷新list页面
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
                this.$parent.$parent.$parent.$parent.getList()
              }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  if (valid) {
                    this.loading = true
                    // 新增数据时 如果没有配置流程，则将审批状态设置为审批完成
                    if (!this.useProcess && !this.form.id) {
                      this.form.actStatus = 'W'
                    }
                    saveDealAfterInvestEvaluation(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                            this.form.id = response.data.id
                            // 启动流程
                            this.startProcess(response.data)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            this.closeForm()
                          }
                          resolve()
                        } else {
                            this.msgError(response.msg)
                            this.loading = false
                            reject()
                        }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    this.locationError(document)
                  }
                })
              })
            },
          // 启动流程
          startProcess: async function(data) {
            var dealName = await getDealName(this.$route.query.id)
            this.loading = false
            // 启动流程时候传入的参数
            const processData = {}
            // 待办标题
            processData.title = '「' + dealName + '」' + ': ' + this.selectDictLabel(this.itemTypeOptions, this.form.itemType) + '-' + '投后评价'
            // 业务表名
            processData.dataTable = 'deal_after_invest_evaluation'
            // 业务ID
            processData.dataId = data.id
            // 业务表单地址(待办页面需要打开的页面)
            processData.formPath = '@/views/deal/afterInvest/dealAfterInvestEvaluationForm'
            // 菜单标识(根据菜单标识判断的走哪个流程)
            processData.menuKey = this.menuKey
            this.startProcessByMenu(processData, () => {
              this.form.actStatus = 'D'
              this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
              this.$store.dispatch('app/toggleExtraProcess', false)
              this.closeForm()
            })
          },
          // 获取是否使用流程
          getUseProcess() {
            getMenuProcess('after_evaluation').then(response => {
              this.useProcess = !!response.data
            })
          }

        }

    }
</script>
